package zcw.com.lib_leet_code;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 朱城委 on 2021/7/12.<br><br>
 *
 * 同构字符串
 */
public class Topic205 {

    public static void main(String[] args) {
        Topic205 instance = new Topic205();

        System.out.println(instance.isIsomorphic("egg", "add"));
        System.out.println(instance.isIsomorphic("foo", "bar"));
        System.out.println(instance.isIsomorphic("paper", "title"));
        System.out.println(instance.isIsomorphic("badc", "baba"));
    }

    public boolean isIsomorphic(String s, String t) {
        char[] map = new char[256];
        boolean[] used = new boolean[256];

        char[] arrayS = s.toCharArray();
        char[] arrayT = t.toCharArray();

        for(int i = 0; i < arrayS.length; i++) {
            if(map[arrayS[i]] == 0) {
                if(used[arrayT[i]]) {
                    return false;
                }

                map[arrayS[i]] = arrayT[i];
                used[arrayT[i]] = true;
            }
            else if(map[arrayS[i]] != arrayT[i]) {
                return false;
            }
        }

        return true;
    }

    public boolean isIsomorphic2(String s, String t) {
        Map<Character, Character> map = new HashMap<>();
        for(int i = 0; i < s.length(); i++) {
            char chS = s.charAt(i);
            char chT = t.charAt(i);

            if(!map.containsKey(chS) && !map.containsValue(chT)) {
                map.put(chS, chT);
            }
            else if(map.get(chS) == null || map.get(chS) != chT) {
                return false;
            }
        }

        return true;
    }
}
